<template>
  <div class="main">
    <p  class="main_text">广告管理</p>
    <div class="cyr-flex">
      <div class="mb20">
      <el-button type="primary" @click="showAddVisibleDalog">添加广告</el-button>
      <el-button type="danger" @click="delAllBtn">批量删除</el-button>
      </div>
      <div class="cyr-flex-box">
      <el-table
        @selection-change="handleSelectionChange"
        :data="tableData"
        :header-cell-style="{background: '#f0f6fe'}"  :show-overflow-tooltip="true" v-adaptive border>
        <el-table-column type="selection" width="40" />
        <el-table-column prop="id" label="编号" />
        <el-table-column prop="name" label="广告名称" />
        <el-table-column prop="displayArea" label="广告位置" />
        <el-table-column prop="limitTimeS" label="开始时间" />
        <el-table-column prop="limitTimeE" label="结束时间" />
        <el-table-column label="上线/下线" prop="status">
          <template #default="props">
            <el-tag type="primary" v-if="props.row.status == 1">上线</el-tag>
            <el-tag type="danger" v-if="props.row.status == 0">下线</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120"  :show-overflow-tooltip="false">
          <template #default="props">
            <el-button type="primary" link size="small" @click="editBtn(props.row)">编辑</el-button>
            <el-button type="danger" link size="small" @click="delBtn(props.row.id)">删除</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="note" label="备注" />
      </el-table>
      <!-- 分页器 -->
      <smartPager
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        @change="handleCurrentChange" />
      </div>
    </div>
  </div>
  <!------------------------------- 添加广告 ------------------------------->
  <el-drawer v-model="addVisibleDalog" :with-header="false" class="drawer" size="600" @close="closeAddVisibleDalog">
    <div class="title_pop" v-if="!imgFlag">添加广告</div>
    <div class="title_pop" v-else>编辑广告</div>
    <div class="pop_topic">基础信息</div>
    <el-form
      ref="ruleFormRef"
      :model="addFormData"
      label-width="120px"
      label-position="top"
      :rules="rules"
      v-if="showAddFormFlag">
      <el-form-item label="广告名称" prop="name">
        <el-input type="text" placeholder="请输入广告名称" v-model="addFormData.name" style="width: 100%" />
      </el-form-item>
      <el-form-item label="广告位置" prop="displayArea">
        <el-select v-model="addFormData.displayArea" placeholder="请选择广告位置" style="width: 100%" filterable>
          <el-option label="商城小程序" value="商城小程序" />
          <el-option label="商城首页" value="商城首页" />
        </el-select>
      </el-form-item>
      <el-form-item label="开始时间" prop="limitTimeStart">
        <el-date-picker
          v-model="addFormData.limitTimeStart"
          type="datetime"
          :disabled-date="disableDate"
          :default-time="defaultTime(0, 0, 0)"
          value-format="YYYY-MM-DDTHH:mm:ss"
          placeholder="请选择开始时间"
          style="width: 100%" />
      </el-form-item>
      <el-form-item label="结束时间" prop="limitTimeEnd">
        <el-date-picker
          v-model="addFormData.limitTimeEnd"
          type="datetime"
          :disabled-date="disableDate1"
          :default-time="defaultTime(0, 0, 0)"
          value-format="YYYY-MM-DDTHH:mm:ss"
          placeholder="请选择结束时间"
          style="width: 100%" />
      </el-form-item>
      <el-form-item label="上线/下线" prop="status">
        <el-select v-model="addFormData.status" placeholder="请选择状态" style="width: 100%" filterable>
          <el-option label="上线" value="1" />
          <el-option label="下线" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="应用商铺" prop="shopId">
        <el-select v-model="addFormData.shopId" placeholder="请选择应用商铺" style="width: 100%" filterable>
          <el-option v-for="item in shopList" :key="item.shop.id" :label="item.shop.shopName" :value="item.shop.id" />
        </el-select>
      </el-form-item>
      <div class="pop_topic">广告内容</div>
      <el-form-item label="广告banner图片" prop="url">
        <div class="photoBox">
          <el-upload
            v-if="!imgFlag"
            action="#"
            list-type="picture-card"
            :auto-upload="false"
            v-model:file-list="fileList"
            :limit="1"
            :on-change="changeFile">
            <el-icon>
              <Plus />
            </el-icon>
          </el-upload>
          <div v-else>
            <el-upload
              action="#"
              list-type="picture-card"
              :auto-upload="false"
              v-model:file-list="fileList"
              :limit="1"
              :on-change="changeFile"
              class="imgUp">
              <el-icon>
                <Plus />
              </el-icon>
            </el-upload>
            <div style="height: 122px"></div>
            <img class="img" :src="addFormData.url" alt="" />
          </div>
        </div>
      </el-form-item>
      <el-form-item label="广告跳转图片" prop="jumpFile" v-if="addFormData.displayArea == '商城小程序'">
        <div class="photoBox">
          <el-upload
            v-if="!imgFlag"
            action="#"
            list-type="picture-card"
            :auto-upload="false"
            v-model:file-list="addFormData.jumpFile"
            :limit="1">
            <el-icon>
              <Plus />
            </el-icon>
          </el-upload>
          <div v-else>
            <el-upload
              action="#"
              list-type="picture-card"
              :auto-upload="false"
              v-model:file-list="addFormData.jumpFile">
              <el-icon>
                <Plus />
              </el-icon>
              <template #file="{file}">
                <div>
                  <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
                  <span class="el-upload-list__item-actions">
                    <el-popconfirm
                      confirm-button-text="是"
                      cancel-button-text="否"
                      :icon="InfoFilled"
                      icon-color="#626AEF"
                      title="是否确认删除?"
                      @confirm="removeJumpFile(file)">
                      <template #reference>
                        <el-icon>
                          <Delete />
                        </el-icon>
                      </template>
                    </el-popconfirm>
                  </span>
                </div>
              </template>
            </el-upload>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="备注" prop="result">
        <el-input v-model="addFormData.note" type="textarea" placeholder="备注" :autosize="{minRows: 3, maxRows: 10}" />
      </el-form-item>
    </el-form>
    <div class="btn_center">
      <el-button class="hollow" @click="addVisibleDalog = false">取消</el-button>
      <el-button class="solid" @click="addSaveBtn(ruleFormRef)" :loading="loading">确认</el-button>
    </div>
  </el-drawer>
</template>
<script setup lang="ts">
import {Plus, Delete} from '@element-plus/icons-vue';
import {ref, onMounted, reactive, watch, onBeforeUnmount} from 'vue';
import {formatTimeAllA} from '@/filters/index';
import {ElMessage} from 'element-plus';
import {ElInput} from 'element-plus';
import {InfoFilled, Edit, ArrowDown, ArrowUp} from '@element-plus/icons-vue';
import type {UploadProps} from 'element-plus';
import {
  RequestAdvertisementGetPageList,
  Requestadvertisementsave,
  RequestShopPageList,
  RequestAdvertisementaDeleteList,
  RequestUploadPlatFormImgs,
} from '@/api/path/index.js';
const loading = ref<any>(false);
const addVisibleDalog = ref<any>(false);
/* ************************ 分页获取数据 ************************ */
const tableData = ref<any>([]);
const total = ref<any>(0);
const currentPage = ref<any>(1);
const pageSize = ref<any>(10);
const handleSizeChange = (val: number) => {
  getData();
};
const handleCurrentChange = (val: number) => {
  getData();
  console.log('tableData.value ', tableData.value);
};
const timeToTimestamp = (time: any) => {
  let timestamp = Date.parse(new Date(time).toString());
  return timestamp;
};
const defaultTime = (H: any, M: any, S: any) => {
  var now = new Date();
  now.setHours(H);
  now.setMinutes(M);
  now.setSeconds(S);
  return now;
};
const disableDate = (time: any) => {
  if (addFormData.value.limitTimeEnd != null) {
    return time.getTime() < Date.now() - 8.64e7 || time.getTime() > timeToTimestamp(addFormData.value.limitTimeEnd);
  } else {
    return time.getTime() < Date.now() - 8.64e7;
  }
};
const disableDate1 = (time: any) => {
  return time.getTime() < timeToTimestamp(addFormData.value.limitTimeStart);
};
const getData = () => {
  RequestAdvertisementGetPageList({
    page: currentPage.value,
    rows: pageSize.value,
  }).then((res: any) => {
    // console.log(res.resultObj);
    total.value = res.resultObj.count;
    res.resultObj.list.forEach((item: any) => {
      item.limitTimeE = item.limitTimeEnd;
      item.limitTimeS = item.limitTimeStart;
    });
    tableData.value = res.resultObj.list;
  });
};
getData();
/* ************************ 添加广告 ************************ */
const shopList = ref<any>([]);
const imgFlag = ref<any>(false); //
const showAddVisibleDalog = () => {
  console.log(addFormData.value);
  // addFormData.value.status=String(addFormData.value.status)
  if (addFormData.value.name == null) {
    imgFlag.value = false;
  } else {
    imgFlag.value = true;
  }
  console.log(imgFlag.value);
  showAddFormFlag.value = true;
  addVisibleDalog.value = true;
  RequestShopPageList({
    page: 1,
    rows: 100000000,
  }).then((res: any) => {
    shopList.value = res.resultObj.shopList;
  });
};
const fileList = ref<any>([]); //banner图片
const changeFile = async (file: any) => {
  addFormData.value.url = await FileToBase64(file.raw);
};
const ruleFormRef = ref<any>();
const rules = ref<any>({
  name: [{required: true, message: '请输入广告名称', trigger: 'blur'}],
  displayArea: [{required: true, message: '请选择广告使用位置', trigger: 'change'}],
  limitTimeStart: [{required: true, message: '请选择开始时间', trigger: 'change'}],
  status: [{required: true, message: '请选择状态', trigger: 'change'}],
  limitTimeEnd: [{required: true, message: '请选择结束时间', trigger: 'change'}],
  jumpFile: [{required: true, message: '请选择广告跳转图片', trigger: 'change'}],
  shopId: [{required: true, message: '请选择应用商铺', trigger: 'change'}],
  url: [{required: true, message: '请选择广告banner图片', trigger: 'change'}],
});
const addFormData = ref<any>({
  name: null, //广告名称
  displayArea: null, //广告位置
  limitTimeStart: null, //开始时间
  limitTimeEnd: null, //结束时间
  jumpUrl: null, //广告链接
  shopId: null, //应用商铺
  status: null, //应用商铺
  url: null, //广告图片
  note: null, //备注
  jumpFile: [], //跳转图片
});
const showAddFormFlag = ref<any>(true);
const closeAddVisibleDalog = () => {
  showAddFormFlag.value = false;
  addFormData.value.name = null;
  addFormData.value.displayArea = null;
  addFormData.value.limitTimeStart = null;
  addFormData.value.limitTimeEnd = null;
  addFormData.value.jumpUrl = null;
  addFormData.value.shopId = null;
  addFormData.value.url = null;
  addFormData.value.id = null;
  addFormData.value.status = null;
  addFormData.value.note = null;
  addFormData.value.jumpFile = [];
  fileList.value = [];
  getData();
};
const addSaveBtn = async (formEl: any) => {
  console.log('当前参数', addFormData.value.jumpFile);
  if (!formEl) return;
  await formEl.validate(async (valid: any) => {
    if (valid) {
      if (addFormData.value.jumpFile.length != 0) {
        if (addFormData.value.jumpFile[0].raw) {
          const formimgs = new FormData();
          formimgs.append('imgs', addFormData.value.jumpFile[0].raw);
          const a = await RequestUploadPlatFormImgs(formimgs);
          if (a.length != 0) {
            addFormData.value.jumpUrl = a[0];
          } else {
            ElMessage.error('跳转图片上传失败！');
          }
          console.log('zzzzzzzzzzzz', addFormData.value);
        }
      }

      if (addFormData.value.createdAt) {
        delete addFormData.value.createdAt;
      }
      delete addFormData.value.limitTimeS;
      delete addFormData.value.limitTimeE;
      addFormData.value.limitTimeStart = formatTimeAllA(addFormData.value.limitTimeStart);
      addFormData.value.limitTimeEnd = formatTimeAllA(addFormData.value.limitTimeEnd);
      addFormData.value.status = Number(addFormData.value.status);
      if (addFormData.value.url.indexOf('http://cyrimageoss.oss') !== -1) {
        delete addFormData.value.url;
      }
      loading.value = true;
      Requestadvertisementsave(addFormData.value).then((res: any) => {
        if (res.success == true) {
          ElMessage.success(res.msg);
          addVisibleDalog.value = false;
          loading.value = false;
          getData();
        } else {
          ElMessage.error(res.msg);
          loading.value = false;
        }
      });
    }
  });
};
/* ************************ 编辑 ************************ */
const editId = ref<any>();
const editBtn = (e: any) => {
  editId.value = e.id;
  if (e.name == null) {
    imgFlag.value = false;
  } else {
    imgFlag.value = true;
  }
  RequestShopPageList({
    page: 1,
    rows: 100000000,
  }).then((res: any) => {
    shopList.value = res.resultObj.shopList;
  });
  console.log(imgFlag.value);
  showAddFormFlag.value = true;
  addVisibleDalog.value = true;
  addFormData.value = e;
  addFormData.value.jumpFile = [{url: addFormData.value.jumpUrl}];
};
const removeJumpFile = (file: any) => {
  addFormData.value.jumpFile = [];
};
/* ************************ 转base64 ************************ */
const ids = ref<any>([]);
const handleSelectionChange = (val: any) => {
  val.forEach((item: any) => ids.value.push(item.id));
};
const delBtn = (id: any) => {
  ids.value.push(id);
  const formimgs = new FormData();
  formimgs.append('ids', ids.value);
  RequestAdvertisementaDeleteList(formimgs).then((res: any) => {
    console.log(res);
    if (res.success == true) {
      ElMessage.success(res.msg);
      getData();
      ids.value = [];
    }
  });
};
const delAllBtn = () => {
  const formimgs = new FormData();
  formimgs.append('ids', ids.value);
  RequestAdvertisementaDeleteList(formimgs).then((res: any) => {
    console.log(res);
    if (res.success == true) {
      ElMessage.success(res.msg);
      getData();
      ids.value = [];
    }
  });
};
/* ************************ 转base64 ************************ */
const FileToBase64 = (file: any) => {
  return new Promise((resolve, reject) => {
    let reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = async function (e) {
      resolve(e.target!.result);
    };
  });
};
</script>
<style lang="scss" scoped>
.main {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  .top {
    width: 100%;
    background-color: #fff;
  }

  .content {
    width: 100%;
    background-color: #fff;
  }
}

.drawer {
  .title_pop {
    font-size: 16px;
    color: #303133;
    font-weight: bold;
  }

  .pop_topic {
    background: #f5f7fa;
    font-size: 14px;
    color: #1d2129;
    line-height: 32px;
    margin-top: 28px;
    margin-bottom: 10px;
    font-weight: normal;
    padding: 0 8px;
  }
}

.photoBox {
  position: relative;
  width: 122px;
  height: 122px;
  overflow: hidden;

  .img {
    width: 122px;
    height: 122px;
    border-radius: 4px;
    position: absolute;
    top: 0;
    z-index: 100;
  }
}

.imgUp {
  opacity: 0;
  position: absolute;
  top: 0;
  z-index: 200;
}
</style>
